import { EditModal } from '@ycx/ui';
import { useTheme } from '@/store/settingsStore.ts';
import { App, DatePicker, Form, Input } from 'antd';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import MaintenancePlanServices, { DelayParams } from '@/api/services/maintenancePlanServices.ts';
import { useMutation } from '@tanstack/react-query';
import dayjs, { Dayjs } from 'dayjs';

export type DelayModalRef = {
  open: (id: number) => void;
};

type Props = {
  onSuccess: () => void;
};

const DelayModal = forwardRef<DelayModalRef, Props>(({ onSuccess }, ref) => {
  const { message } = App.useApp();
  const theme = useTheme();
  const [form] = Form.useForm<Omit<DelayParams, 'id'> & { delayTime: Dayjs }>();

  const id = useRef<number>();
  const [open, setOpen] = useState(false);

  const { mutate, isPending } = useMutation({
    mutationFn: MaintenancePlanServices.delay,
    onSuccess: () => {
      message.success('延期成功');
      close();
      onSuccess();
    },
    onError: (error) => {
      message.error(error.message);
    },
  });

  const handleSubmit = async () => {
    await form.validateFields();
    const data = form.getFieldsValue();
    mutate({ ...data, id: id.current!, delayTime: data.delayTime.format('YYYY-MM-DD HH:mm:ss') });
  };

  const close = () => {
    setOpen(false);
    id.current = undefined;
    form.resetFields();
  };

  useImperativeHandle(ref, () => ({
    open: (_id) => {
      id.current = _id;
      setOpen(true);
    },
  }));

  return (
    <EditModal
      title="延期处理"
      theme={theme}
      open={open}
      onClose={close}
      onCancel={close}
      forceRender
      confirmLoading={isPending}
      onOk={handleSubmit}
      modalRender={(dom) => (
        <Form form={form} layout="vertical" initialValues={{ userBlock: false }}>
          {dom}
        </Form>
      )}
    >
      <Form.Item
        label="延期时间"
        name="delayTime"
        rules={[{ required: true, message: '请选择延期时间' }]}
      >
        <DatePicker
          className="w-full"
          placeholder="请选择延期时间"
          disabledDate={(current) => {
            return current.valueOf() < dayjs().subtract(1, 'day').valueOf();
          }}
        />
      </Form.Item>
      <Form.Item
        label="延期原因"
        name="delayReason"
        rules={[{ required: true, message: '请输入延期原因' }]}
      >
        <Input placeholder="请输入延期原因" />
      </Form.Item>
      <Form.Item label="备注" name="delayRemark">
        <Input.TextArea placeholder="请输入备注" autoSize={{ minRows: 3 }} />
      </Form.Item>
    </EditModal>
  );
});

export default DelayModal;
